//
//  UIKWaitingView.swift
//  UIKWaitingView
//
//  Created by Fineland on 2021/3/18.
//

class UIKWaitingView: UIView {
    
    //背景
    private var mskView: UIView!
    //图片、内容
    private var imageView: UIImageView!
    private var infoLabel: UILabel!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //创建视图
        setupViews(in: frame.size)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func show(_ isShow: Bool = true) -> Void {
        
        //显示/隐藏？
        self.isHidden = !isShow
        if true != isShow {
            imageView.layer.removeAnimation(forKey: "rotationAlways")
            return
        }
        //开始旋转动画
        let animation = CABasicAnimation(keyPath: "transform.rotation.z")
        animation.fromValue = 0.0
        animation.toValue = 2.0 * CGFloat.pi
        animation.duration = 1.0
        animation.autoreverses = false
        animation.fillMode = CAMediaTimingFillMode.forwards
        animation.repeatCount = MAXFLOAT
        animation.isRemovedOnCompletion = false
        //添加
        imageView.layer.add(animation, forKey: "rotationAlways")
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    private func setupViews(in size: CGSize) -> Void {
        
        //遮罩层
        let realSize = CGSize(width: 180.0, height: 124.0)
        mskView = UIView(frame: CGRect(origin: CGPoint(x: 0.5 * (size.width - realSize.width),
                                                       y: 0.5 * (size.height - realSize.height)),
                                       size: realSize))
        mskView.alpha = 0.8
        mskView.backgroundColor = UIColor.black
        mskView.layer.cornerRadius = 4.0
        mskView.clipsToBounds = true
        
        let hLabel: CGFloat = 16.0
        let whImg: CGFloat = 64.0
        let spaceVal: CGFloat = 20.0
        //等待图片
        imageView = UIImageView(frame: CGRect(x: 0.5 * (size.width - whImg),
                                              y: mskView.frame.origin.y + spaceVal,
                                              width: whImg, height: whImg))
        imageView.image = UIImage(named: "system_waiting")
        //文本
        infoLabel = UILabel(frame: CGRect(x: mskView.frame.origin.x, y: imageView.frame.maxY + 0.5 * spaceVal,
                                          width: realSize.width, height: hLabel))
        infoLabel.text = "加载中..."
        infoLabel.font = UIFont.boldSystemFont(ofSize: 15.0)
        infoLabel.textAlignment = .center
        infoLabel.textColor = UIColor.white
        //添加
        self.addSubview(mskView)
        self.addSubview(imageView)
        self.addSubview(infoLabel)
    }
}

// MARK: -

private struct AssociatedKey {
    
    //请求等待
    static var WAITING: String = "Http_Request_Waitting"
}

// MARK: -

extension UIViewController {
    
    private var waitingView: UIKWaitingView? {
        
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.WAITING) as? UIKWaitingView
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.WAITING, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    func showWaiting(_ isWaiting: Bool = true) -> Void {
        
        //是否为空？
        if nil == self.waitingView {
            //是否有tabBar？
            let hBar: CGFloat = self.tabBarController?.tabBar.frame.size.height ?? 0.0
            let hNavi: CGFloat = self.navigationController!.navigationBar.frame.size.height
            let hStatus: CGFloat = UIApplication.shared.windows.first!.windowScene?.statusBarManager?.statusBarFrame.size.height ?? 0.0
            let hMinus = hBar + hNavi + hStatus
            //RECT值
            var rect = self.navigationController!.view.bounds
            rect.size.height -= hMinus
            //创建
            let tempView = UIKWaitingView(frame: rect)
            self.waitingView = tempView
            //添加
            self.view.addSubview(tempView)
        }
        //等待时：所有事件不可用
        self.view.isUserInteractionEnabled = !isWaiting
        //显示/隐藏？
        self.waitingView!.show(isWaiting)
    }
}
